<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="用户名" style="width: 200px;" class="filter-item"
                @keyup.enter.native="handleFilter"/>

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>

      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleAdd">
        新增
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID" prop="id" align="center" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="头像" align="center" min-width="150px">
        <template slot-scope="{row}">
          <img :src="row.avatar" width="100px" height="100px">
        </template>
      </el-table-column>

      <el-table-column label="管理员名称" align="center" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="角色" align="center" min-width="150px">
        <template slot-scope="{row}">
          <el-tag class="tag"
                  :key="role.id"
                  v-for="role in row.roles"
                  :disable-transitions="false">
            {{role.roleName}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button circle size="small" icon="el-icon-edit" @click="handleEdit(row)">
          </el-button>

          <el-button type="danger" circle size="small" icon="el-icon-delete" @click="handleDelete(row)">
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.curPageNum" :limit.sync="listQuery.pageSize"
                @pagination="getList"/>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form ref="dataForm" :rules="rules" :model="defaultForm" label-position="left" label-width="70px"
               style="margin-left:50px;">
        <el-form-item label="名称" prop="name">
          <el-input v-model="defaultForm.name" style="width:250px"/>
        </el-form-item>

        <el-form-item label="头像" prop="avatar" style="margin-bottom: 30px;">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8280/file"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="defaultForm.avatar" :src="defaultForm.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>

        <div v-if="!isEdit">
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="defaultForm.password" style="width:250px"/>
          </el-form-item>

          <el-form-item label="重复密码" prop="confirmPassword">
            <el-input type="password" v-model="defaultForm.confirmPassword" style="width:250px"/>
          </el-form-item>
        </div>
        <el-form-item label="角色" prop="role" style="margin-bottom: 30px;">
          <el-checkbox-group v-model="checkboxGroup" size="small" style="width:350px" @change="changeCheckBox">
            <el-checkbox border style="margin: 0 10px 10px 0;" v-for="item in roleList" :key="item.id" :label="item.id">
              {{item.roleName}}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>


      </el-form>

      <div slot="footer">
        <el-button @click="cancelDialog">
          取消
        </el-button>
        <el-button type="primary" @click="isEdit?updateData():createData()">
          确定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {fetchList, saveManager, updateManager, deleteManager} from '@/api/manager'
  import {getRoles} from '@/api/role'
  import waves from '@/directive/waves' // waves directive
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination

  export default {
    name: 'Manager',
    components: {Pagination},
    directives: {waves},
    data() {
      return {
        checkboxGroup: [],
        tempRow:{},
        tempRole:[],//解决checkBoxGroup只能放integer才能回显的造成取消不能正确显示的问题
        roleList: [],
        isEdit: false,
        dialogTitle: '',
        dialogVisible: false,
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          curPageNum: 1,
          pageSize: 10,
          name: undefined
        },
        defaultForm: {
          id: undefined,
          name: '',
          avatar: '',
          roles: null
        },

        dialogStatus: '',
        //检验规则
        rules: {
          type: [{required: true, message: 'type is required', trigger: 'change'}],
          timestamp: [{type: 'date', required: true, message: 'timestamp is required', trigger: 'change'}],
          title: [{required: true, message: 'title is required', trigger: 'blur'}]
        },
        downloadLoading: false
      }
    },
    created() {
      this.getList()
      this.getRoles()
    },
    methods: {
      getList() {
        this.listLoading = true
        fetchList(this.listQuery).then(response => {
          this.list = response.data.list
          this.total = response.data.total
          this.listLoading = false
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleDelete(row) {

        this.$confirm('确定要删除该管理员?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async() => {
            await deleteManager(row.id)
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
            this.$message({
              type: 'success',
              message: '删除成功'
            })
          })
          .catch(err => { console.error(err) })

      },
      handleAdd() {
        this.dialogTitle = '新增'
        this.dialogVisible = true
        this.isEdit = false
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
        //新增重置为空
        this.checkboxGroup = []
        this.defaultForm = {
          id: undefined,
          name: '',
          avatar: '',
          roles: null
        }

      },
      handleEdit(row) {
        this.isEdit=true
        this.dialogTitle = '编辑'
        this.defaultForm = Object.assign({}, row)
        let roleIds = this.defaultForm.roles.map(function (item) {
          return item['id']
        });
        this.checkboxGroup = roleIds
        this.defaultForm.roles = this.checkboxGroup
        this.dialogVisible = true
      },
      handleAvatarSuccess(e) {
        this.defaultForm.avatar = e.data.url
      },
      changeCheckBox(e) {
        this.defaultForm.roles = this.checkboxGroup
      },
      getRoles() {
        getRoles().then(r1 => {
          this.roleList = r1.data
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const postForm = Object.assign({}, this.defaultForm)
            console.log("更新数据", postForm)
            updateManager(postForm).then(() => {
              //重新获取表数据
              this.getList()
              this.dialogVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },

      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            saveManager(this.defaultForm).then(() => {
              this.getList()
              this.dialogVisible = false
              this.$notify({
                title: '成功',
                message: '新增成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },

      cancelDialog(){
        //取消
        this.dialogVisible = false;
        // this.row.roleList = this.tempRole

      }
    }
  }
</script>

<style lang="scss" scoped>
  /*图片*/
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    border: 1px solid #d9d9d9;
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    border: 1px solid #d9d9d9;
    width: 178px;
    height: 178px;
    display: block;
  }

  .tag {
    margin-left: 5px;
  }
</style>
